package com.gaowl.yygh.sms.controller;

import com.alibaba.excel.util.StringUtils;
import com.gaowl.yygh.commom.result.Result;
import com.gaowl.yygh.sms.service.SmsService;
import com.gaowl.yygh.sms.utils.RandomUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/sms")
public class SmsApiController {

    @Autowired
    private SmsService smsService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    @GetMapping("send/{phone}")
    @ApiOperation(value="向手机发送验证码")
    public Result sendCode(@PathVariable("phone") String phone){
        // 先到Redis中查看是否已存在该手机号对应的验证码
        System.out.println(phone+"\n\n");
        String code = redisTemplate.opsForValue().get(phone);  // key为phone，val为code
        if (!StringUtils.isEmpty(code)){
            return Result.ok();
        }
        // 如果没有，则为该手机号生成验证码，并设置有效时间
        code = RandomUtil.getSixBitRandom();
        boolean isSend = smsService.send(phone, code);// 调用service层方法，向该手机号发送验证码
        if(isSend) {
            redisTemplate.opsForValue().set(phone,code,2, TimeUnit.MINUTES);  // 有效时间2分钟
            return Result.ok();
        } else {
            return Result.fail().message("发送短信失败");
        }

    }

}
